package test.solution;

import com.google.gson.Gson;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import java.util.HashMap;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Created on 2016/6/24.
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class Solution1 {

    public static final Gson gson = new Gson();

    @Test
    public void test() {
        String pattern = "abba";
        String str = "dog cat cat dog";

        assertTrue(wordPattern("abba", "dog cat cat dog"));
        assertFalse(wordPattern("abba", "dog cat cat fish"));
        assertFalse(wordPattern("aaaa", "dog cat cat dog"));
        assertFalse(wordPattern("abba", "dog dog dog dog"));

    }

    public boolean wordPattern(String pattern, String str) {

        if (isBlank(pattern) && isBlank(str)) {
            return true;
        } else if (isBlank(pattern) || isBlank(str)) {
            return false;
        }

        String[] ss = str.split(" ");
        if (ss.length != pattern.length()) {
            return false;
        }

        HashMap<Character, String> map = new HashMap<Character, String>();
        for (int i = 0; i < pattern.length(); i++) {
            Character c = pattern.charAt(i);
            if (map.containsKey(c)) {
                if (!map.get(c).equals(ss[i])) {
                    return false;
                } else {
                    continue;
                }
            } else {
                if (map.containsValue(ss[i])) {
                    return false;
                } else {
                    map.put(c, ss[i]);
                }
            }
        }

        return true;
    }

    public static boolean isBlank(String str) {
        return str == null || str == "";
    }
}
